#!/usr/bin/python3
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QShortcut
from PyQt5.QtGui import QKeySequence
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtGui import QCursor
from PyQt5.QtCore import Qt
import mainwindow as main_window
import sys
import serial
import serial.tools.list_ports
import time
import robot
import os


APP = QtWidgets.QApplication(sys.argv)
MAINWINDOW = QtWidgets.QMainWindow()
UI = main_window.Ui_MainWindow()
UI.setupUi(MAINWINDOW)
SERIAL = serial.Serial()

ROBOT_1 = robot.Robot(SERIAL)  
ROBOT_2 = robot.Robot(SERIAL)

PORT_MANAGER = robot.PortManager()
PORT_MANAGER_2 = robot.PortManager()

SELECTED_PORT_NAME_1 = None
SELECTED_PORT_NAME_2 = None
CURSOR = UI.textBrowser.textCursor()

with open("./QSS/ElegantDark.qss", "r") as f:
    APP.setStyleSheet(f.read())
# APP.setStyleSheet("./QSS/Ubuntu.qss")

def hm_print(text):
    CURSOR.insertText(str(text)+"\n")

def func_for_show_ports(*args):
    """Robot1展示可用端口的函数"""
    UI.comboBox.setItemText(0, "断开连接")
    last_ports = PORT_MANAGER.ports.copy()
    ports, names = PORT_MANAGER.get_ports()
    for k, i in enumerate(last_ports):
        # 删除已不存在的端口
        if i not in ports:
            UI.comboBox.removeItem(k+1)
            if last_ports:
                last_ports.pop(k)
    
    for k, i in enumerate(ports):
        # 添加新出现的端口
        if ports[k] not in last_ports:
            UI.comboBox.addItem(i)
            if last_ports:
                last_ports.append(ports[k])
    UI.comboBox.showPopup()

def func_for_select_port(*args):
    """Robot1选择端口的函数"""
    global SELECTED_PORT_NAME_1
    index = args[0]
    if index == 0:  #点击断开连接的时候做的事情
        ROBOT_1.set_speed(0, 0)
        ROBOT_1.set_speed(1, 0)
        ROBOT_1.set_speed(2, 0)
        ROBOT_1.set_speed(3, 0)
        ROBOT_1.disconnect()
        UI.horizontalSlider_X.setValue(0)
        UI.horizontalSlider_Y.setValue(0)
        UI.horizontalSlider_X1.setValue(0)
        UI.horizontalSlider_Z1.setValue(0)
        UI.horizontalSlider_X.setEnabled(False)
        UI.horizontalSlider_Y.setEnabled(False)
        UI.horizontalSlider_X1.setEnabled(False)
        UI.horizontalSlider_Z1.setEnabled(False)
        SELECTED_PORT_NAME_1 = None
    else:
        # port_name = PORT_MANAGER.name_to_port(UI.comboBox.currentText())
        port_name = UI.comboBox.currentText()
        SELECTED_PORT_NAME_1 = port_name
        hm_print(SELECTED_PORT_NAME_1)
        



def func_for_show_ports_2(*args):
    """Robot2展示可用端口的函数"""
    UI.comboBox_2.setItemText(0, "断开连接")
    last_ports = PORT_MANAGER_2.ports.copy()
    ports, names = PORT_MANAGER_2.get_ports()
    for k, i in enumerate(last_ports):
        # 删除已不存在的端口
        if i not in ports:
            UI.comboBox_2.removeItem(k+1)
            if last_ports:
                last_ports.pop(k)
    
    for k, i in enumerate(ports):
        # 添加新出现的端口
        if ports[k] not in last_ports:
            UI.comboBox_2.addItem(i)
            if last_ports:
                last_ports.append(ports[k])
    UI.comboBox_2.showPopup()

def func_for_scan_wifi(*args):
    result = os.popen("ifconfig")  
    # os.system("reboot")
    # print(result.read())
    UI.textBrowser.insertPlainText(result.read())

    


def func_for_select_port_2(*args):
    """Robot2选择端口的函数"""
    global SELECTED_PORT_NAME_2
    index = args[0]
    if index == 0:
        ROBOT_2.set_speed(0, 0)
        ROBOT_2.set_speed(1, 0)
        ROBOT_2.set_speed(2, 0)
        ROBOT_2.set_speed(3, 0)
        ROBOT_2.disconnect()
        UI.horizontalSlider_1.setValue(0)
        UI.horizontalSlider_2.setValue(0)
        UI.horizontalSlider_3.setValue(0)
        UI.horizontalSlider_4.setValue(0)
        UI.horizontalSlider_1.setEnabled(False)
        UI.horizontalSlider_2.setEnabled(False)
        UI.horizontalSlider_3.setEnabled(False)
        UI.horizontalSlider_4.setEnabled(False)
        SELECTED_PORT_NAME_2 = None
    else:
        # port_name = PORT_MANAGER_2.name_to_port(UI.comboBox_2.currentText())
        port_name = UI.comboBox_2.currentText()
        SELECTED_PORT_NAME_2 = port_name
        # UI.textBrowser.insertPlainText(SELECTED_PORT_NAME_2)
        hm_print(SELECTED_PORT_NAME_2)



def func_for_stop(slider, robot, idx):
    slider.setValue(0)
    robot.set_speed(idx, 0)

def func_for_all_stop():
    UI.horizontalSlider_X.setValue(0)
    UI.horizontalSlider_Y.setValue(0)
    UI.horizontalSlider_X1.setValue(0)
    UI.horizontalSlider_Z1.setValue(0)
    UI.horizontalSlider_1.setValue(0)
    UI.horizontalSlider_2.setValue(0)
    UI.horizontalSlider_3.setValue(0)
    UI.horizontalSlider_4.setValue(0)
    ROBOT_1.set_speed(0, 0)
    ROBOT_1.set_speed(1, 0)
    ROBOT_1.set_speed(2, 0)
    ROBOT_1.set_speed(3, 0)
    ROBOT_2.set_speed(0, 0)
    ROBOT_2.set_speed(1, 0)
    ROBOT_2.set_speed(2, 0)
    ROBOT_2.set_speed(3, 0)
    UI.textBrowser.clear()


def func_for_tab_click(*args):
    idx = args[0]
    if idx == 0:
        # serial被点击要做的事情
        func_for_all_stop()
        ROBOT_1.disconnect()
        ROBOT_2.disconnect()
        ...
    elif idx == 1:
        # robot1被点击要做的事情
        ROBOT_2.disconnect()
        if SELECTED_PORT_NAME_1 is not None:
            ROBOT_1.connect(SELECTED_PORT_NAME_1)
            UI.horizontalSlider_X.setEnabled(True)
            UI.horizontalSlider_Y.setEnabled(True)
            UI.horizontalSlider_X1.setEnabled(True)
            UI.horizontalSlider_Z1.setEnabled(True)
    elif idx == 2:
        # robot2被点击要做的事情
        
        ROBOT_1.disconnect()
        if SELECTED_PORT_NAME_2 is not None:
            ROBOT_2.connect(SELECTED_PORT_NAME_2)
            UI.horizontalSlider_1.setEnabled(True)
            UI.horizontalSlider_2.setEnabled(True)
            UI.horizontalSlider_3.setEnabled(True)
            UI.horizontalSlider_4.setEnabled(True)



def bind_methods():
    # 串口按钮设置命令
    UI.comboBox.mousePressEvent = func_for_show_ports
    UI.comboBox.currentIndexChanged.connect(func_for_select_port)
    UI.tabWidget.tabBarClicked.connect(func_for_tab_click)
    UI.comboBox.wheelEvent=lambda *args: None
    UI.comboBox_2.mousePressEvent = func_for_show_ports_2
    UI.comboBox_2.currentIndexChanged.connect(func_for_select_port_2) 
    UI.comboBox_2.wheelEvent=lambda *args: None
    #步进电机按钮设置命令
    UI.horizontalSlider_X.valueChanged.connect(lambda *args: ROBOT_1.set_speed(0, args[0]))
    UI.stop_x.clicked.connect(lambda *args: func_for_stop(UI.horizontalSlider_X,ROBOT_1,0))
    UI.horizontalSlider_Y.valueChanged.connect(lambda *args: ROBOT_1.set_speed(1, args[0]))
    UI.stop_y.clicked.connect(lambda *args: func_for_stop(UI.horizontalSlider_Y,ROBOT_1,1))
    UI.horizontalSlider_X1.valueChanged.connect(lambda *args: ROBOT_1.set_speed(2, args[0]))
    UI.stop_x1.clicked.connect(lambda *args: func_for_stop(UI.horizontalSlider_X1,ROBOT_1,2))
    UI.horizontalSlider_Z1.valueChanged.connect(lambda *args: ROBOT_1.set_speed(3, args[0]))
    UI.stop_z1.clicked.connect(lambda *args: func_for_stop(UI.horizontalSlider_Z1,ROBOT_1,3))
    UI.horizontalSlider_1.valueChanged.connect(lambda *args: ROBOT_2.set_speed(0, args[0]))
    UI.stop_1.clicked.connect(lambda *args: func_for_stop(UI.horizontalSlider_1,ROBOT_2,0))
    UI.horizontalSlider_2.valueChanged.connect(lambda *args: ROBOT_2.set_speed(1, args[0]))
    UI.stop_2.clicked.connect(lambda *args: func_for_stop(UI.horizontalSlider_2,ROBOT_2,1))
    UI.horizontalSlider_3.valueChanged.connect(lambda *args: ROBOT_2.set_speed(2, args[0]))
    UI.stop_3.clicked.connect(lambda *args: func_for_stop(UI.horizontalSlider_3,ROBOT_2,2))
    UI.horizontalSlider_4.valueChanged.connect(lambda *args: ROBOT_2.set_speed(3, args[0]))
    UI.stop_4.clicked.connect(lambda *args: func_for_stop(UI.horizontalSlider_4,ROBOT_2,3))

    #舵机按钮设置命令
    # UI.x_up.clicked.connect(lambda *args:ROBOT_2.set_position(3) )
    # UI.x_down.clicked.connect(lambda *args:ROBOT_2.set_position(4) )
    # UI.x1_up.clicked.connect(lambda *args:ROBOT_2.set_position(5) )
    # UI.x1_down.clicked.connect(lambda *args:ROBOT_2.set_position(6) )
    # UI.y_up.clicked.connect(lambda *args:ROBOT_2.set_position(7) )
    # UI.y_down.clicked.connect(lambda *args:ROBOT_2.set_position(8) )
    UI.stop_all.clicked.connect(func_for_all_stop)
    UI.start.clicked.connect(func_for_scan_wifi)



def main():
    if not os.name == 'nt':
        APP.setOverrideCursor(Qt.BlankCursor)
    UI.horizontalSlider_X.setEnabled(False)
    UI.horizontalSlider_Y.setEnabled(False)
    UI.horizontalSlider_X1.setEnabled(False)
    UI.horizontalSlider_Z1.setEnabled(False)
    UI.horizontalSlider_1.setEnabled(False)
    UI.horizontalSlider_2.setEnabled(False)
    UI.horizontalSlider_3.setEnabled(False)
    UI.horizontalSlider_4.setEnabled(False)
    bind_methods()
    MAINWINDOW.closeEvent = at_exit
    MAINWINDOW.show()
    sys.exit(APP.exec_())

def at_exit(*args):
    ...

if __name__ == "__main__":
    print("start GUI")
    main()


